import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../controllers/product_spec_modal_controller.dart';

/// 商品规格选择弹窗
class ProductSpecModalView extends GetView<ProductSpecModalController> {
  const ProductSpecModalView({super.key});

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: const BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(20),
          topRight: Radius.circular(20),
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          // 顶部商品信息区域
          _buildProductInfoSection(),
          // 规格选择区域
          _buildSpecSelectionSection(),
          // 底部操作按钮
          _buildActionButton(),
        ],
      ),
    );
  }

  /// 构建商品信息区域
  Widget _buildProductInfoSection() {
    return Container(
      padding: EdgeInsets.all(16.w),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 商品图片
          Container(
            width: 100.w,
            height: 100.w,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(10.r),
              image: DecorationImage(
                image: CachedNetworkImageProvider(controller.productImage),
                fit: BoxFit.cover,
              ),
            ),
          ),
          SizedBox(width: 12.w),
          // 商品信息
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 商品名称
                Text(
                  controller.productName,
                  style: TextStyle(
                    fontSize: 16.sp,
                    fontWeight: FontWeight.bold,
                    color: Colors.black,
                  ),
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                ),
                SizedBox(height: 8.h),
                // 选中规格
                Obx(
                  () => Text(
                    controller.selectedSpecs.values.join(' '),
                    style: TextStyle(fontSize: 14.sp, color: Colors.grey[600]),
                  ),
                ),
                SizedBox(height: 8.h),
                // 价格和数量选择器
                Row(
                  children: [
                    // 价格
                    Text(
                      '¥${controller.productPrice}',
                      style: TextStyle(
                        fontSize: 18.sp,
                        fontWeight: FontWeight.bold,
                        color: Colors.orange,
                      ),
                    ),
                    const Spacer(),
                    // 数量选择器
                    _buildQuantitySelector(),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 构建数量选择器
  Widget _buildQuantitySelector() {
    return Container(
      decoration: BoxDecoration(
        border: Border.all(color: Colors.grey[300]!),
        borderRadius: BorderRadius.circular(4.r),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          // 减少按钮
          InkWell(
            onTap: controller.decreaseQuantity,
            child: Container(
              width: 20.w,
              height: 20.w,
              decoration: BoxDecoration(
                color: Colors.grey[100],
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(4.r),
                  bottomLeft: Radius.circular(4.r),
                ),
              ),
              child: Icon(Icons.remove, size: 16.sp, color: Colors.blue),
            ),
          ),
          // 数量输入框
          Container(
            width: 50.w,
            height: 20.w,
            decoration: BoxDecoration(
              color: Colors.white,
              border: Border.symmetric(
                vertical: BorderSide(color: Colors.grey[300]!),
              ),
            ),
            child: TextField(
              controller: controller.quantityController,
              textAlign: TextAlign.center,
              keyboardType: TextInputType.number,
              maxLines: 1,
              inputFormatters: [
                FilteringTextInputFormatter.digitsOnly,
                LengthLimitingTextInputFormatter(5),
              ],
              style: TextStyle(fontSize: 12.sp),
              decoration: const InputDecoration(
                border: InputBorder.none,
                contentPadding: EdgeInsets.zero,
                isCollapsed: true,
              ),
              onChanged: (value) {
                final intValue = int.tryParse(value);
                if (intValue != null && intValue >= 1) {
                  controller.setQuantity(intValue);
                }
              },
            ),
          ),
          // 增加按钮
          InkWell(
            onTap: controller.increaseQuantity,
            child: Container(
              width: 20.w,
              height: 20.w,
              decoration: BoxDecoration(
                color: Colors.grey[100],
                borderRadius: BorderRadius.only(
                  topRight: Radius.circular(4.r),
                  bottomRight: Radius.circular(4.r),
                ),
              ),
              child: Icon(Icons.add, size: 16.sp, color: Colors.blue),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建规格选择区域
  Widget _buildSpecSelectionSection() {
    return Obx(
      () => Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: controller.specGroups.map((group) {
          return Container(
            padding: EdgeInsets.symmetric(horizontal: 16.w),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                SizedBox(height: 16.h),
                // 规格名称
                Text(
                  group.name,
                  style: TextStyle(
                    fontSize: 16.sp,
                    fontWeight: FontWeight.bold,
                    color: Colors.black,
                  ),
                ),
                SizedBox(height: 12.h),
                // 规格选项
                Wrap(
                  spacing: 12.w,
                  runSpacing: 12.h,
                  children: group.options.map((option) {
                    final isSelected =
                        controller.selectedSpecs[group.name] == option.name;
                    return GestureDetector(
                      onTap: option.isAvailable
                          ? () => controller.selectSpec(group.name, option.name)
                          : null,
                      child: Container(
                        padding: EdgeInsets.symmetric(
                          horizontal: 16.w,
                          vertical: 8.h,
                        ),
                        decoration: BoxDecoration(
                          color: isSelected ? Colors.blue : Colors.white,
                          border: Border.all(
                            color: isSelected ? Colors.blue : Colors.grey[300]!,
                            width: 1,
                          ),
                          borderRadius: BorderRadius.circular(4.r),
                        ),
                        child: Text(
                          option.name,
                          style: TextStyle(
                            fontSize: 14.sp,
                            color: isSelected ? Colors.white : Colors.black,
                            fontWeight: isSelected
                                ? FontWeight.bold
                                : FontWeight.normal,
                          ),
                        ),
                      ),
                    );
                  }).toList(),
                ),
              ],
            ),
          );
        }).toList(),
      ),
    );
  }

  /// 构建底部操作按钮
  Widget _buildActionButton() {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.all(16.w),
      child: Obx(() {
        int count = controller.quantity.value;
        if (controller.modalType == 'cart') {
          // 加入购物车按钮
          return ElevatedButton(
            onPressed: controller.confirmAction,
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.blue,
              foregroundColor: Colors.white,
              padding: EdgeInsets.symmetric(vertical: 16.h),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(8.r),
              ),
            ),
            child: Text(
              '加入购物车',
              style: TextStyle(fontSize: 16.sp, fontWeight: FontWeight.bold),
            ),
          );
        } else {
          // 立即购买按钮
          return ElevatedButton(
            onPressed: controller.confirmAction,
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.orange,
              foregroundColor: Colors.white,
              padding: EdgeInsets.symmetric(vertical: 16.h),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(8.r),
              ),
            ),
            child: Text(
              '¥${controller.productPrice}',
              style: TextStyle(fontSize: 16.sp, fontWeight: FontWeight.bold),
            ),
          );
        }
      }),
    );
  }
}
